<template>
  <div>
    <el-card class="form-card">
      <el-form ref="formRef" :inline="true">
        <el-form-item label="门店信息">
          <MultipleSelect style="min-width: 15rem" v-model="storeIds" :options="storeOptions" placeholder="请选择门店"/>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker v-model="pickerDate"
                          :shortcuts="pickerShortcuts"
                          style="margin-right: 16px;width: 15rem"
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD"
                          start-placeholder="开始日期"
                          type="daterange"
                          :clearable="false"
                          value-format="YYYY-MM-DD"/>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-row class="panel-group" :gutter="8">
      <el-col :md="6" :sm="12" class="card-panel-col">
        <card-panel :decimals="0"
                    :model-value="statisticsData.quantity"
                    icon-class="ribbon"
                    icon-style="style3"
                    panel-text="订单总数">
        </card-panel>
      </el-col>

      <el-col :md="6" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.amount"
                    icon-class="money"
                    icon-style="style1"
                    panel-text="订单总额">
        </card-panel>
      </el-col>

      <el-col :md="6" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.integral"
                    icon-class="rose"
                    icon-style="style2"
                    panel-text="花朵总额">
        </card-panel>
      </el-col>

      <el-col :md="6" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.consume_gold_payed"
                    icon-class="ribbon"
                    icon-style="style4"
                    panel-text="消费金抵扣总额">
        </card-panel>
      </el-col>
    </el-row>


    <el-row :gutter="9">
      <el-col :md="18" :sm="24" style="margin-bottom: 9px">
        <el-card class="content-card">
          <template #header>
            <span>消费趋势</span>
          </template>
          <div class="chart-warp">
            <VChart :loading="loading" :option="chartsOption" autoresize/>
          </div>
        </el-card>
      </el-col>

      <el-col :md="6" :sm="24" style="margin-bottom: 9px">
        <el-card class="content-card">
          <template #header>
            <span>门店消费排名</span>
          </template>
          <el-scrollbar class="ranking" height="400px">
            <li v-if="storeDataList.length > 0" v-for="(item, index) in storeDataList">
              <el-text truncated>
                <span :class="{ circle: true, active: index < 3 }">{{ index + 1 }}</span>
              </el-text>
              <div class="flex1 ml-3">
                <div style="display: flex" class="progress">
                  <el-progress class="flex1" :stroke-width="12" :text-inside="true" :percentage="item.percent"/>
                  <span style="flex:.35;text-align: right">{{ formatNumericToWan(item.amount) }}</span>
                </div>
                <span class="line-ellipsis-2 flex">{{ item.name }}</span>
              </div>
            </li>
            <el-empty v-else :image-size="64" description="暂无数据"/>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>

    <div class="region-warp">
      <el-row :gutter="9">
        <el-col :md="12" style="margin-bottom: 9px">
          <el-card class="content-card">
            <template #header>
              <span>地域消费分布</span>
            </template>
            <VChart :loading="loading" :option="option" autoresize class="echarts-region"/>
          </el-card>
        </el-col>

        <el-col :md="12" style="margin-bottom: 9px">
          <el-card class="content-card">
            <template #header>
              <span>门店类目分析</span>
              <div class="card-header-extra">
              </div>
            </template>
            <VChart :loading="loading" :option="pieOption" autoresize class="echarts-region"/>
            <!--            <el-table v-loading="loading" :data="storeDataList" fit highlight-current-row class="echarts-region">
                          <el-table-column type="index" width="50" label="序号"/>

                          <el-table-column align="right" label="门店" prop="name" min-width="160">
                          </el-table-column>

                          <el-table-column align="right" label="消费总额" prop="amount" min-width="120">
                            <template #default="scope">
                              {{ formatNumericToWan(scope.row.amount) }}
                            </template>
                          </el-table-column>

                          <el-table-column align="right" label="占比率" prop="percent" min-width="160">
                            <template #default="scope">
                              <el-progress :stroke-width="9" :percentage="scope.row.percent"/>
                            </template>
                          </el-table-column>
                        </el-table>-->
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">

import { formatNumericToWan, pickerShortcuts } from '@/utils';
import { computed, onBeforeMount, provide, reactive, ref } from 'vue';
import VChart, { THEME_KEY } from 'vue-echarts';
import useLoading from '@/hooks/use-loading.ts';
import dayjs from 'dayjs';
import '@/utils/echarts.ts'
import { ChartsSeriesData, SalesProportionData, statisticStoreOrderCharts } from '@/api/dashboard.ts';
import { BaseShopData } from '@/api/common.ts';
import { storeSimpleList } from '@/api/api-store.ts';
import { CardPanel, MultipleSelect } from '@/components/other';
import { DictItem } from '@/utils/global-dict.ts';
import { useDark } from '@vueuse/core';

defineOptions({name: 'statistic-store-order'});

const isDark = useDark();
const eChartTheme = computed(() => (isDark.value ? 'dark' : ''));
provide(THEME_KEY, eChartTheme);

// 查询
const queryFormData = reactive({
  ids: undefined,
  // 时间范围 格式 2023-01-01~2023-01-31
  date: undefined,
});
const pickerDate = ref<any[]>([]);
const [loading, setLoading] = useLoading(true);

const option = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: function (params: any) {
        return [
          params.name,
          '消费总额：' + (params.value || 0),
        ].join('<br>');
      }
    },
    // 左侧小导航图标
    visualMap: {
      show: true,
      min: regionMinNum.value,
      max: regionMaxNum.value,
      text: ['高', '低'],
      inRange: {
        color: ['#D8FAFE', '#1a53ff']
      }
    },
    // 配置属性
    series: [
      {
        type: 'map',
        mapType: 'china',
        roam: true,
        scaleLimit: {
          min: 1.0
        },
        label: {
          normal: {
            show: false // 是否显示省份名称
          },
          emphasis: {
            show: true,
          }
        },
        itemStyle: {
          normal: {
            label: {
              show: true
            },
            borderWidth: .5,
            borderColor: '#1a53ff',

          },
          emphasis: {
            borderWidth: 1,
            borderColor: '#1a53ff',
            shadowColor: '#FC8A4E',
            shadowBlur: 10,
            zoom: 3,
          }
        },
        data: regionDataList.value
      }
    ]
  };
});

const chartsOption = computed(() => {
  return {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    legend: {
      data: legendData.value,
    },
    toolbox: {
      show: true,
      showTitle: false,
      feature: {
        mark: {show: true},
        magicType: {show: true, type: ['line', 'bar', 'tiled']},
        restore: {show: true},
        saveAsImage: {show: true}
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData.value,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: true,
        alignWithLabel: true,
      },
      // axisLabel: {
      //   interval: 0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
      //   rotate: 38   //调整数值改变倾斜的幅度（范围-90到90）
      // }
    },
    yAxis: {
      type: 'value'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    series: seriesData.value,
  };
});

/** 饼图 类目数据 */
const pieOption = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      top: 'top',
      type: 'scroll',
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        itemStyle: {
          borderRadius: 6
        },
        data: cateDataList.value,
        label: {
          show: true,
          formatter: '{b}: {d}%' // 显示名称和百分比
        },
        //avoidLabelOverlap: false, // 是否启用防止标签重叠策略，默认开启，
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
      },
    ],
  };
});

// 图表数据
const legendData = ref<string[]>([]);
const xAxisData = ref<string[]>([]);
const seriesData = ref<any[]>([]);

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

onBeforeMount(() => {
  // 加载门店数据
  initStoreData();
  // 重置查询表单
  handleResetQueryForm();
});

/** 统计数据 */
const statisticsData = reactive({
  quantity: 0,
  amount: 0,
  integral: 0,
  cash_payed: 0,
  coupon_payed: 0,
  consume_gold_payed: 0,
});

/**
 * 数据查询
 */
const fetchDataList = async () => {
  if (!pickerDate.value || pickerDate.value.length != 2) {
    return
  }
  setLoading(true);
  try {
    // 时间范围参数
    // @ts-ignore
    queryFormData.date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined
    // 门店编号集合
    // @ts-ignore
    queryFormData.ids = storeIds.value.join(',');
    // 查询数据
    const {data} = await statisticStoreOrderCharts(queryFormData);

    // 统计信息
    statisticsData.quantity = data.statistics.quantity;
    statisticsData.amount = data.statistics.amount;
    statisticsData.integral = data.statistics.integral;
    statisticsData.cash_payed = data.statistics.cash_payed;
    statisticsData.coupon_payed = data.statistics.coupon_payed;
    statisticsData.consume_gold_payed = data.statistics.consume_gold_payed;

    // 解析图表数据
    let charts = data.charts || [];
    let dateList: string[] = [];
    let seriesData_1: any[] = [], seriesData_2: any[] = [], seriesData_3: any[] = [], seriesData_4: any[] = [], seriesData_5: any[] = [];
    charts.forEach(it => {
      dateList.push(it.date);
      seriesData_1.push(it.quantity);
      seriesData_2.push(it.amount);
      seriesData_3.push(it.integral);
      seriesData_4.push(it.coupon_payed);
      seriesData_5.push(it.consume_gold_payed);
    });

    legendData.value = ['订单总数', '订单总额', '花朵支付', '消费金抵扣'];
    xAxisData.value = dateList;
    seriesData.value = [
      {name: '订单总数', type: 'line', smooth: true, data: seriesData_1,},
      {name: '订单总额', type: 'line', smooth: true, data: seriesData_2,},
      {name: '花朵支付', type: 'line', smooth: true, data: seriesData_3,},
      // {name: '消费券抵扣', type: 'line', smooth: true, data: seriesData_4,},
      {name: '消费金抵扣', type: 'line', smooth: true, data: seriesData_5,},
    ]

    // 区域消费数据
    let regions = data.regions || [];
    let numbers: number[] = [];
    let dataListX: SalesProportionData[] = [];
    regions.forEach(it => {
      numbers.push(it.amount);
      dataListX.push({name: it.name, value: it.amount})
    })
    regionDataList.value = dataListX;
    regionMinNum.value = Math.min(...numbers) || 0;
    regionMaxNum.value = Math.max(...numbers) || 10;

    // 门店消费排名
    storeDataList.value = data.stores;

    // 类目数据
    let cateList = data.cates || [];
    let dataListCate: SalesProportionData[] = [];
    cateList.forEach(it => {
      dataListCate.push({name: it.name, value: it.amount})
    })
    cateDataList.value = dataListCate;
  } catch (err) {
    console.log(err)
  } finally {
    setLoading(false);
  }
};

// 重置查询条件
const handleResetQueryForm = () => {
  let nowDate = new Date();
  let endTime = dayjs(nowDate).format('YYYY-MM-DD');
  let startTime = dayjs(nowDate.setDate(nowDate.getDate() - 30)).format('YYYY-MM-DD');
  pickerDate.value = [startTime, endTime];
  storeIds.value = [];
  regionDataList.value = [];
  regionMinNum.value = 0;
  regionMaxNum.value = 100;
  storeDataList.value = [];
  cateDataList.value = [];
  handleSearch();
};

interface RegionData {
  code: number
  name: string
  amount: number
  percent: number
}

const regionDataList = ref<ChartsSeriesData[]>([]);
const regionMinNum = ref(0);
const regionMaxNum = ref(100);
const storeDataList = ref<RegionData[]>([]);
const cateDataList = ref<ChartsSeriesData[]>([]);

/** 加载店铺数据 */
const storeIds = ref<Number[]>([]);
const storeList = ref<BaseShopData[]>([]);
const storeOptions = ref<DictItem[]>([]);
const storeLoading = ref(false)
const initStoreData = async () => {
  storeLoading.value = true
  try {
    const {data} = await storeSimpleList({});
    storeList.value = data || []
    storeList.value.forEach(it => storeOptions.value.push({value: it.id, label: it.name}))
  } finally {
    storeLoading.value = false
  }
};

</script>

<style scoped lang="scss">
.chart-warp {
  height: 400px;
  width: 100%;
}

.region-warp {
  min-height: 400px;
  width: 100%;
}

.echarts-region {
  height: 400px;
  width: 100%;
}

:deep() {
  .el-progress__text {
    font-size: var(--el-font-size-base) !important;
  }
}

.ranking {
  list-style-type: none;
  padding: 0;
  margin: 0;
  width: 100%;

  li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 6px;

    .circle {
      width: 24px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      font-size: 12px;

      &.active {
        background-color: var(--el-color-primary-light-9);
      }
    }

    :deep() {
      .el-progress-bar__innerText {
        font-size: 10px;
        margin: 0 5px 2px
      }
    }
  }
}

</style>
